package com.runen.wnhz.runen.ui.activity.major;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.google.gson.Gson;
import com.runen.wnhz.runen.R;
import com.runen.wnhz.runen.bean.WantLearnBean;
import com.runen.wnhz.runen.common.utils.ACacheUtlis;
import com.runen.wnhz.runen.common.utils.NetUtils;
import com.runen.wnhz.runen.common.utils.OkHttpUtils;
import com.runen.wnhz.runen.common.utils.StatusBarCompatUtils;
import com.runen.wnhz.runen.common.utils.ToastUtil;
import com.runen.wnhz.runen.data.entity.UserBean;
import com.runen.wnhz.runen.di.component.ApplicationComponent;
import com.runen.wnhz.runen.ui.activity.BaseActivity;
import com.runen.wnhz.runen.ui.activity.login.LoginForPersonalActivity;
import com.runen.wnhz.runen.widget.TitleBuilder;

import java.io.IOException;

import butterknife.BindView;
import butterknife.OnClick;
import me.zhanghai.android.materialratingbar.MaterialRatingBar;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class UserStarActivity extends BaseActivity {

    @BindView(R.id.ratingBar)
    MaterialRatingBar ratingBar;
    @BindView(R.id.edit_inputStarContent)
    EditText editInputStarContent;
    @BindView(R.id.btn_commitScore)
    Button btnCommitScore;
    private String token;

    private String lid;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutView() {
        return R.layout.activity_user_star;
    }

    @Override
    protected void onTitleClickListen(TitleBuilder.TitleButton clicked) {
        switch (clicked) {
            case LEFT:
                finish();
                break;
            case MIDDLE:
                break;
            case RIGHT:
                break;
            default:
                break;
        }
    }

    @OnClick({R.id.btn_commitScore})
    public void onClickEvent(View view){
        switch (view.getId()){
            case R.id.btn_commitScore:
                float rating = ratingBar.getRating();
                String editStarContent = editInputStarContent.getEditableText().toString().trim();
                if(rating == 0f){
                    ToastUtil.showToast("请选择星评数");
                }else if(TextUtils.isEmpty(editStarContent)){
                    ToastUtil.showToast("请输入评价内容");
                }else{
                   submitUserStar();
                }
                break;
        }
    }

    private void submitUserStar() {
        progressDialog.setMessage("正在提交评分");
        showProgressDialog();
        if (token != null && lid != null) {
            FormBody formBody = new FormBody.Builder().add("token", token).add("lid", lid).add("star_number", String.valueOf(ratingBar.getRating())).add("content",editInputStarContent.getEditableText().toString().trim()).build();
            Request request = new Request.Builder().url(NetUtils.SUBMIT_USER_STAR).post(formBody).build();
            Call newCall = OkHttpUtils.getOkHttpClient().newCall(request);
            newCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dismissDialog();
                            ToastUtil.showToast("提交评分失败");
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        handleUserStarData(response);
                    } catch (IOException e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.showToast("评分提交出现异常");
                                dismissDialog();
                            }
                        });
                    }
                }
            });
        }
    }

    private void handleUserStarData(Response response) throws IOException{
        if(response.isSuccessful()){
            ResponseBody responseBody = response.body();
            final String json = responseBody.string();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    WantLearnBean wantLearnBean = new Gson().fromJson(json, WantLearnBean.class);
                    if("1".equals(wantLearnBean.getRe())){
                        ToastUtil.showToast(wantLearnBean.getInfo());
                        Intent intent = new Intent();
                        intent.putExtra("submit_star_result",true);
                        setResult(Activity.RESULT_OK,intent);
                        finish();
                    }else if("0".equals(wantLearnBean.getRe())){
                        ToastUtil.showToast(wantLearnBean.getInfo());
                    }else if("-1".equals(wantLearnBean.getRe())){
                        ToastUtil.showToast(wantLearnBean.getInfo());
                        startActivity(new Intent(UserStarActivity.this, LoginForPersonalActivity.class));
                    }
                    dismissDialog();
                }
            });
        }

    }

    @Override
    protected void initStart() {
        StatusBarCompatUtils.getInstance().TranslucentStatusBar(this, R.color.title_green);
        ACacheUtlis cacheUtlis = ACacheUtlis.getInstance();
        if (cacheUtlis != null) {
            UserBean reqeustUser = cacheUtlis.getReqeustUser(this);
            if (reqeustUser != null) {
                token = reqeustUser.getToken();
            }
        }
        lid = getIntent().getStringExtra("lid");
    }

    @Override
    public void initToolBar(TitleBuilder mTitleBuilder) {
        mTitleBuilder.setMiddleTitleText("评价")
                .setLeftDrawable(R.mipmap.icon_back)
                .seTitleBgRes(R.mipmap.bg_title)
                .setMiddleTitleTextColor(ContextCompat.getColor(this, R.color.text_white));
    }

    @Override
    public void setupAcitivtyComponent(ApplicationComponent appComponent) {

    }
}
